<?php


namespace api\project\controller;


use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;


class OrderController extends RestBaseController
{
    public function createOrder(Request $request)
    {
        $data = input('post.');
        $user_id = $request->user_id;
        $goods = Db::name('goods')
            ->where('id','=',$data['goods_id'])
            ->find();
        if(!$goods)
        {
            $this->error('商品不存在');
        }
//        halt(json_decode($goods['info'],'ture'));
        $res = $this->GetPrice2($goods,$data['goods_info']);
        if(!$res)
        {
            $this->error('商品不存在');
        }
        $price = $res['价格'];
        $address = Db::name('address')
            ->where('user_id','=',$user_id)
            ->find();
        if($goods['status'] !=1)
        {
            $this->error('商品缺货');
        }
        $insert_data =[];
        $trade_no = date('YmdHis').mt_rand(1111,9999);
        $insert_data[]=[
            'user_id'=>$user_id,
            'goods_name'=>$goods['name'],
            'goods_info'=>json_encode($data['goods_info'],JSON_UNESCAPED_UNICODE),
            'price'=>$price,
            'num'=>$data['num'],
            'total_price'=>$price * $data['num'],
            'trade_no'=>$trade_no,
            'user_name'=>$address['address_user'],
            'user_address'=>$address['address'],
            'user_tel'=>$address['mobile'],
            'status'=>0,
            'remarks'=>$data['remarks'],
            'create_time'=>date('Y:m:d H:i:s')
        ];

        $res = Db::name('order')
            ->insertAll($insert_data);
        if($res){
            $this->success('订单创建成功',['order_id'=>$trade_no]);
        }else{
            $this->error('失败');
        }
    }
    private function GetPrice($good_id,$goods_info)
    {
        $goods = Db::name('goods')
            ->where('id','=',$good_id)
            ->find();
        $info = json_decode($goods['info'],true);
        foreach ($info as $val)
        {
            if($val['尺码']==$goods_info['尺码'] && $val['颜色']==$goods_info['颜色']){
                return $val;
            }
        }
    }
    private function GetPrice2($goods,$goods_info)
    {
        $info = json_decode($goods['info'],true);
        foreach ($info as $sku){
            $hasSKu = true;
            foreach ($goods_info as $key => $val){
                if($sku[$key] != $val){
                    $hasSKu = false;
                }
            }
            if($hasSKu){
                return $sku;
            }else{
                continue;
            }
        }
    }
}